# -*- coding: utf-8 -*-
# Created by liangfuting on 2020/6/27
# Copyright (c) 2020 liangfuting. All rights reserved.
import re
from django.utils.module_loading import import_string
from collections import OrderedDict
from django.conf import settings
from django.urls import URLPattern,URLResolver
from django.http import QueryDict

def check_url_exclude(url):
    #排除名名单中的url
    exclude_url=settings.AUTO_DISCOVER_EXCLUDE

    for regex in exclude_url:
        if re.match(regex,url):
            return True


def get_all_url_dict():
    # 获取项目中所有的url(必须有别名name)
    url_order_dict = OrderedDict()
    """
    md = {
        'rbac:menu_list':{'name':"rbac:menu_list",'url':"rbac/menu_list"},
    }
    """
    md = import_string(settings.ROOT_URLCONF)#以字符串的形式加载urls配置
    #RegexURLResolver 路由分发
    #RegexURLPattern 路由条目
    #初始根namespace为空的
    # recursion_urls(None,'/',md.urlpatterns,url_order_dict)
    recursion_urls2(None, '/', md.urlpatterns,url_order_dict)
    # print(url_order_dict)
    #如果碰到路由条目则中止，如果是路由分发则继续循环
    return url_order_dict

def recursion_urls2(pre_namespace,pre_url,urlpatterns,url_order_dict):
    for item in urlpatterns:
        if isinstance(item,URLPattern):#非路由分发，将路由添加到url_ordered_dict中
            # print('item', type(item))
            # print(item)
            # print('name:',item.name,'url:',item.pattern)
            if not item.name:
                #如果没有名字就忽略
                continue

            if pre_namespace:
                if item.name:
                    namespace = "%s:%s" % (pre_namespace, item.name)
                else:
                    namespace = item.name
            else:
                namespace = item.name

            if item.pattern:
                pattern = "%s%s" % (pre_url, item.pattern)
            else:
                pattern = item.pattern
            pattern=pattern.replace("^","").replace("$","")
            # print("name",namespace,'pattern',pattern)
            if check_url_exclude(pattern):
                continue
            url_order_dict[namespace]={'name':namespace,'url':pattern}
        if isinstance(item,URLResolver):
            # print('item', type(item))
            # print(item.namespace,item.pattern)
            # print('item url_patterns',item.url_patterns)
            if item.namespace =="admin":
                continue

            if pre_namespace:
                if item.namespace:
                    namespace= "%s:%s"%(pre_namespace,item.namespace)
                else:
                    namespace=item.namespace
            else:
                namespace=item.namespace

            if item.pattern:
                pattern="%s%s" %(pre_url,item.pattern)
            else:
                pattern=item.pattern
            recursion_urls2(namespace,pattern,item.url_patterns,url_order_dict)


def recursion_urls(pre_namespace,per_url,urlpatterns,url_ordered_dict):
    """
    递归的去获取url
    pre_namespace,namespace
    per_url, namespace前缀
    urlpatterns,路由关系列表
    url_ordered_dict用于保存递归中的所有路由
    :return:
    """
    for item in urlpatterns:

        if isinstance(item,URLPattern):#非路由分发，将路由添加到url_ordered_dict中
            print('item', type(item))
            # print(item)
            print(item.pattern,item.name)
            # if not item.name:
            #     continue
            # name=item.name
            # if pre_namespace:
            #     name="%s:%s" %(pre_namespace,item.name)
            # else:
            #     name=item.name
            # url=per_url+item._regex #/^rbac/^user/edit/(?P<pk>\d+)/
            # url=url.replace("^","").replace("$","")#去掉起始符和结束符


            # url_ordered_dict[name] ={'name':name,'url':}

        elif isinstance(item,URLResolver):#如果是路由发发的话，递归操作
            # print('item', type(item))
            print("item pattern",item.pattern)
            # print('item urlconf_name',item.urlconf_name,item.urlconf_module)
            # print('item namespace',item.namespace,item.namespace_dict)
            # print('item app_name',item.app_name,item.app_dict)
            print('item url_patterns',item.url_patterns)#显示所属的url pattern路由条目
            # print('item url_pattern',item.url_pattern)
            for sub_item in item.url_patterns:
                if isinstance(sub_item,URLResolver):
                    print("item pattern:",sub_item.pattern)
                    print('item url_patterns:', sub_item.url_patterns)
                    # print('item resolve',item.reverse_dict)

            # if pre_namespace:
            #     if item.namespace:
            #         namespace= "%s:%s"%(pre_namespace,item.namespace)
            #     else:
            #         namespace=item.namespace
            # else:
            #     namespace=item.namespace

            # recursion_urls(namespace,per_url,urlpatterns,url_ordered_dict)
